using System;
using System.Security;
using System.Security.Principal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Be.Timvw.Framework.Security;

namespace Be.Timvw.Framework.Tests.Security.Principal.WindowsIdentityHelper
{
    [TestClass]
    public class WhenGettingWindowsIdentity
    {
        [TestMethod]
        public void ShouldHaveImpersonatedUserAsCurrentWindowsIdentity()
        {
            string username = LocalAccountInfo.ValidUsername;
            string domain = Environment.MachineName;
            SecureString password = SecureStringHelper.Create(LocalAccountInfo.ValidPassword);

            using(Framework.Security.Principal.WindowsIdentityHelper windowsIdentityHelper = new Framework.Security.Principal.WindowsIdentityHelper(username, domain, password))
            {
                using(windowsIdentityHelper.GetWindowsIdentity().Impersonate())
                {
                    WindowsIdentity current = WindowsIdentity.GetCurrent();
                    if(current == null)
                    {
                        Assert.Fail("Current WindowsIdentity is null.");
                    }
                    else
                    {
                        string actual = current.Name;

                        string expected = string.Format(@"{0}\{1}", Environment.MachineName, username);

                        Assert.AreEqual(expected, actual);
                    }
                }
            }
        }

        [TestMethod, ExpectedException(typeof(ArgumentException))]
        public void ShouldThrowIfAlreadyDisposed()
        {
            string username = LocalAccountInfo.ValidUsername;
            string domain = Environment.MachineName;
            SecureString password = SecureStringHelper.Create(LocalAccountInfo.ValidPassword);

            Framework.Security.Principal.WindowsIdentityHelper windowsIdentityHelper = new Framework.Security.Principal.WindowsIdentityHelper(username, domain, password);
            windowsIdentityHelper.Dispose();
            windowsIdentityHelper.GetWindowsIdentity();
        }
    }
}